You are given a phone number as a string number. number consists of digits, spaces ' ', and/or dashes '-'.
You would like to reformat the phone number in a certain manner. Firstly, remove all spaces and dashes. Then, group the digits from left to right into blocks of length 3 until there are 4 or fewer digits. The final digits are then grouped as follows:
2 digits: A single block of length 2.
3 digits: A single block of length 3.
4 digits: Two blocks of length 2 each.
The blocks are then joined by dashes. Notice that the reformatting process should never produce any blocks of length 1 and produce at most two blocks of length 2.
Return the phone number after formatting.
遺憾的是,我遇到的第一個問題是題目看不懂,所以先丟去翻譯!
雖然腦袋中有一點思路了,
但實際開始寫程式時卻感到異常生疏、寫下這些就花了近40分鐘...
import java.util.Scanner;
public class Solution {
public String reformatNumber(String number) {
// 1. 移除空格和破折號,思路是一個個檢查字串如果是空格或破折號就跳過
String st = "";
for (char c : number.toCharArray()) {
if (c == ' ' || c == '-') {
continue;
}
// 只儲存數字
st += c;
}
// 2. 分組
String result = "";
int i = 0;
int j = st.length();
// 依次將數字分成長度為3的組,並添加破折號
while (j - i > 4) {
result += st.substring(i, i + 3) + "-";
i += 3;
}
// 處理剩下的數字
if (j - i == 4) {
result += st.substring(i, i + 2) + "-" + st.substring(i + 2);
} else {
result += st.substring(i);
}
return result;
}
}
迎面而來的第二個問題是,物件寫好後不知道psvm要執行什麼?
但總覺得應該要創建一個scanner去接收題目輸入,所以姑且寫了
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// 從輸入讀取字串
String number = scanner.nextLine();
Solution solution = new Solution();
}
然後丟去leetcode執行看看,發現成功了!!
但好奇心使然,我把scanner那兩句刪除後發現一樣可以執行?!
後來想想,其實在leetcode給我的第一行程式就已經賦值number了,我多寫的那段完全是畫蛇添足...
繼續把整個psvm都刪了,結果一樣可以執行,這我就比較疑惑了。
接著去看看別人的正確答案,比我的整潔非~常多!
class Solution {
String modifiedNumber="";
public String reformatNumber(String number) {
modifiedNumber=number.replace(" ","");
modifiedNumber=modifiedNumber.replace("-","");
int l=modifiedNumber.length();
if(l<=3){
return modifiedNumber;
} else if(l==4){
return modifiedNumber.substring(0,2)+"-"+ modifiedNumber.substring(2,4);
} else {
modifiedNumber=modifiedNumber.substring(0,3)+"-"+reformatNumber(modifiedNumber.substring(3,l));
}
return modifiedNumber;
}
}
最後是我的一點小心得,學寫程式真的沒有捷徑,
很多語法沒見過,唯一的辦法就是遇一個新的就學一個新的!
學無止境罷!感謝看到這裡的您!